package thread;

class MyBlockingQueue{
    private String[] items = new String[1000];
    //指向队列的头部
    volatile private int head =0;
    //指向队列尾部的下一个元素，总的来说，队列中有效元素的范围[head，tail）
    //当head和tail相等（重合），相当于队列为空或者队列满，为区分，我们引入了size参数
    volatile private int tail =0;
    //使用size来表示元素个数
    volatile private int size =0;
    //入队列
    public void put(String elem) throws InterruptedException {
        //此处的写法就相当于直接把synchronized写到方法上了
        synchronized (this){
            while (size>=items.length){
                //队列满了
                this.wait();
            }
            items[tail]=elem;
            tail++;
            if(tail>=items.length){
                tail=0;
            }
            size++;
            //用来唤醒队列为空的阻塞情况
            this.notify();
        }
    }
    //出队列
    public String take() throws InterruptedException {
        synchronized(this){
            while (size==0){
                this.wait();

            }
            String elem = items[head];
            head++;
            if(head>=items.length){
                head=0;
            }
            size--;
            this.notify();
            return elem;
        }
    }

}
public class demo2 {
    public static void main(String[] args) throws InterruptedException {
      /*MyBlockingQueue queue=new MyBlockingQueue();
        queue.put("aaa");
        queue.put("bbb");
        queue.put("ccc");
        String elem = queue.take();
        System.out.println(elem);
        elem = queue.take();
        System.out.println(elem);
        elem = queue.take();
        System.out.println(elem);
        elem = queue.take();
        System.out.println("elem="+elem);
     */
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(()->{
           int count = 0;
           while (true){
               try {
                   queue.put(count+"");
                   System.out.println("生产元素："+count);
                   count++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        Thread t2 = new Thread(()->{
           while (true){
               try {
                   String count = queue.take();
                   System.out.println("消费元素："+count);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

           }
        });
        t1.start();
        t2.start();
    }
}
